import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  Image,
  ScrollView,
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import AsyncStorage from '@react-native-async-storage/async-storage';
import DateTimePicker from '@react-native-community/datetimepicker';

const EditProfile = ({ navigation }) => {
  const [profile, setProfile] = useState({
    nickname: '',
    bio: '',
    gender: '',
    birthday: '',
    phone: '',
    profile_picture: '',
  });
  const [showDatePicker, setShowDatePicker] = useState(false);

  // 获取当前用户信息
  useEffect(() => {
    const fetchProfile = async () => {
      try {
        const token = await AsyncStorage.getItem('authToken');
        const response = await fetch('http://124.222.104.145:8003/user/profile/', {
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });
        const data = await response.json();
        setProfile(data);
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    };
    fetchProfile();
  }, []);

  // 处理日期选择
  const onDateChange = (event, selectedDate) => {
    setShowDatePicker(false);
    if (selectedDate) {
      setProfile(prev => ({
        ...prev,
        birthday: selectedDate.toISOString().split('T')[0],
      }));
    }
  };

  // 更新个人资料
  const handleSubmit = async () => {
    try {
      const token = await AsyncStorage.getItem('authToken');
      const response = await fetch('http://124.222.104.145:8003/user/profile/', {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(profile),
      });

      if (response.ok) {
        Alert.alert('成功', '个人资料更新成功', [
          { text: '确定', onPress: () => navigation.goBack() }
        ]);
      } else {
        Alert.alert('错误', '更新失败，请重试');
      }
    } catch (error) {
      console.error('更新个人资料失败:', error);
      Alert.alert('错误', '更新失败，请检查网络连接');
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <Icon name="angle-left" size={30} color="#000" />
        </TouchableOpacity>
        <Text style={styles.title}>修改资料</Text>
      </View>

      <ScrollView style={styles.form}>
        <View style={styles.inputGroup}>
          <Text style={styles.label}>昵称</Text>
          <TextInput
            style={styles.input}
            value={profile.nickname}
            onChangeText={(text) => setProfile(prev => ({ ...prev, nickname: text }))}
            placeholder="请输入昵称"
          />
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>个人简介</Text>
          <TextInput
            style={[styles.input, styles.textArea]}
            value={profile.bio}
            onChangeText={(text) => setProfile(prev => ({ ...prev, bio: text }))}
            placeholder="请输入个人简介"
            multiline
            numberOfLines={4}
          />
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>性别</Text>
          <View style={styles.genderButtons}>
            <TouchableOpacity
              style={[styles.genderButton, profile.gender === '男' && styles.selectedGender]}
              onPress={() => setProfile(prev => ({ ...prev, gender: '男' }))}
            >
              <Text style={profile.gender === '男' ? styles.selectedGenderText : styles.genderText}>男</Text>
            </TouchableOpacity>
            <TouchableOpacity
              style={[styles.genderButton, profile.gender === '女' && styles.selectedGender]}
              onPress={() => setProfile(prev => ({ ...prev, gender: '女' }))}
            >
              <Text style={profile.gender === '女' ? styles.selectedGenderText : styles.genderText}>女</Text>
            </TouchableOpacity>
          </View>
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>生日</Text>
          <TouchableOpacity onPress={() => setShowDatePicker(true)}>
            <Text style={styles.input}>{profile.birthday || '请选择生日'}</Text>
          </TouchableOpacity>
          {showDatePicker && (
            <DateTimePicker
              value={profile.birthday ? new Date(profile.birthday) : new Date()}
              mode="date"
              onChange={onDateChange}
            />
          )}
        </View>

        <View style={styles.inputGroup}>
          <Text style={styles.label}>手机号</Text>
          <TextInput
            style={styles.input}
            value={profile.phone}
            onChangeText={(text) => setProfile(prev => ({ ...prev, phone: text }))}
            placeholder="请输入手机号"
            keyboardType="phone-pad"
          />
        </View>

        <TouchableOpacity style={styles.submitButton} onPress={handleSubmit}>
          <Text style={styles.submitText}>保存修改</Text>
        </TouchableOpacity>
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    padding: 20,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginLeft: 20,
  },
  form: {
    padding: 20,
  },
  inputGroup: {
    marginBottom: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 8,
    color: '#333',
  },
  input: {
    borderWidth: 1,
    borderColor: '#ddd',
    borderRadius: 8,
    padding: 10,
    fontSize: 16,
  },
  textArea: {
    height: 100,
    textAlignVertical: 'top',
  },
  genderButtons: {
    flexDirection: 'row',
    gap: 20,
  },
  genderButton: {
    paddingVertical: 8,
    paddingHorizontal: 20,
    borderRadius: 20,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  selectedGender: {
    backgroundColor: '#366',
    borderColor: '#366',
  },
  genderText: {
    color: '#333',
  },
  selectedGenderText: {
    color: '#fff',
  },
  submitButton: {
    backgroundColor: '#366',
    padding: 15,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 30,
  },
  submitText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
});

export default EditProfile;